package part2.socket.mysocket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;

public class MyServer {
    private ServerSocket serverSocket;
    private ArrayList<PrintWriter> allOut = new ArrayList<>();
    public MyServer(){
        try {
            System.out.println("开始启动服务器");
            serverSocket = new ServerSocket(8088);
            System.out.println("启动服务器成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public void start(){
        try {
            while (true){
                System.out.println("服务器等待连接");
                Socket socket = serverSocket.accept();
                System.out.println("一个客户端连接了");

                ClientHandle handle = new ClientHandle(socket);
                Thread t = new Thread(handle);
                t.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        MyServer myServer = new MyServer();
        myServer.start();

    }


    private class ClientHandle implements Runnable{
        private Socket socket;
        private String host;
        public ClientHandle(Socket socket){
            this.socket = socket;
            host = socket.getInetAddress().getHostAddress();
        }
        @Override
        public void run() {
            PrintWriter pw = null;
            try {
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in);
                BufferedReader br = new BufferedReader(isr);

                OutputStream out = socket.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(out, StandardCharsets.UTF_8);
                BufferedWriter bw = new BufferedWriter(osw);
                pw = new PrintWriter(bw,true);

                synchronized (allOut){
                    allOut.add(pw);
                }

                sendMessage(host+"上线了，当前连接数为:"+allOut.size());

                String message;
                while ((message=br.readLine()) != null){
                   sendMessage(host+"说:"+message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    synchronized (allOut){
                        allOut.remove(pw);
                    }
                    sendMessage(host+"下线了，当前连接数为："+allOut.size());
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


        private void sendMessage(String message){
            System.out.println(message);
            for (PrintWriter p: allOut){
                p.println(message);
            }
        }

    }

}
